package com.itheima.demo;

import java.util.Arrays;
import java.util.Random;

public class Demo_QuiteSort {
    public static void main(String[] args) {
        int[] arr = {11, 2, 4, 5, 7, 8, 9, 23, 56, 8};
        //定义一个快排的方法;
        quiteSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    private static void quiteSort(int[] arr, int left, int right) {
        //递归的出口;
        if (left > right) {
            return;
        }        //为了基准数归位,定义两个变量;
        int left0 = left;
        int right0 = right;
        Random r = new Random();
        int i = r.nextInt(right - left + 1) + left;
        int tmp = arr[i];
        arr[i] = arr[left];
        arr[left] = tmp;

        int number = arr[left];
        //开始循环比较;
        while (left != right) {
            while (arr[right] >= number && left < right) {
                right--;
            }
            while (arr[left] <= number && left < right) {
                left++;
            }
            //交换两个值的位置;
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
        }
        //基准数归位;
        int temp = arr[left];
        arr[left] = arr[left0];
        arr[left0] = temp;

        quiteSort(arr, left0, left - 1);
        quiteSort(arr, left + 1, arr.length - 1);
    }
}
